package com.tian.controller;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.tian.annotation.LoginCheckAnnotation;
import com.tian.common.CommonResult;
import com.tian.dto.WxPrePayReqDto;
import com.tian.enums.ResultCode;
import com.tian.enums.UserUpdatePointEnum;
import com.tian.message.MessageReqIdPrefixConstant;
import com.tian.message.UserPointMessage;
import com.tian.producer.UserPointProducer;
import com.tian.service.ChargePayOrderService;
import com.tian.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * {@code @description:} 支付订单相关操作
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024/2/20 21:26
 * {@code @version:} 1.0
 */
@Slf4j
@RestController
@RequestMapping("/pay")
public class ChargePayOrderController {
    @Resource
    private ChargePayOrderService chargePayOrderService;
    @Resource
    private UserPointProducer userPointProducer;

    /**
     * 生成预支付单
     */
    @PostMapping("/prePay")
    @LoginCheckAnnotation
    public CommonResult<WxPayMpOrderResult> prePay(@RequestBody WxPrePayReqDto wxPrePayReqDto) {
        if (wxPrePayReqDto == null || wxPrePayReqDto.getUserId() == null || wxPrePayReqDto.getAmount() == null) {
            return CommonResult.failed(ResultCode.PARAMETER_EMPTY);
        }
        return chargePayOrderService.prePay(wxPrePayReqDto);
    }

    /**
     * 支付后台通知
     */
    @PostMapping("/wx/notify")
    public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            return chargePayOrderService.payNotify(request, response);
        } catch (Exception e) {
            log.error("会带通知失败，异常信息：", e);
            return "回调异常";
        }
    }

    /**
     * 作为 demo 用，重点是只关注 积分变动这个流程
     */
    @GetMapping("/send")
    public void send() {
        UserPointMessage userPointMessage = new UserPointMessage();
        userPointMessage.setType(UserUpdatePointEnum.ADD.getType());
        userPointMessage.setUserId(1L);
        userPointMessage.setPoint(9);
        userPointMessage.setReqId(MessageReqIdPrefixConstant.USER_POINT_UPDATE_REQ_ID_PREFIX + UUID.randomUUID()+ DateUtils.formatDefaultDateMs());
        userPointProducer.sendMessage(JSON.toJSONString(userPointMessage));
    }

}
